﻿using Forum.Infrastructure;
using Forum.Model;
using Forum.Model.Entity.System;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System.Security.Claims;

namespace Forum.Filter
{
    public class AsyncUserFilter : IAsyncActionFilter
    {
        private CurrentUser? _user;

        public AsyncUserFilter(CurrentUser? user)
        {
            _user = user;
        }

        public async Task OnActionExecutionAsync(
          ActionExecutingContext context,
          ActionExecutionDelegate next)
        {
            var tokenUser = context.HttpContext.User.FindFirst(ClaimTypes.Name)?.Value;
            if (tokenUser is not null)
            {
                var userInfo = JsonConvert.DeserializeObject<SYS_USER>(tokenUser);
                if(userInfo==null)
                    return;
                CurrentUser.UserName = userInfo.UserName;
                CurrentUser.UserId = userInfo.UserId;
                CurrentUser.UserCode = userInfo.UserCode;
                CurrentUser.NickName = userInfo.NickName;
                CurrentUser.Email = userInfo.Email;
                CurrentUser.Tel = userInfo.Tel;
                CurrentUser.Phone = userInfo.Phone;
                CurrentUser.Address = userInfo.Address;
            }

            await next();
        }
    }
}
